//
//  ViewController.swift
//  ZLSwapMenu
//
//  Created by zzl on 01/11/2023.
//  Copyright (c) 2023 zzl. All rights reserved.
//

import UIKit
import ZLSwapMenu

class ViewController: UIViewController {
    // 模拟数据
    var dataArray: Array<Int> = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,19 ,20]
    /// 菜单
    lazy var menu: ZLSwapMenu = {
        let layout = UICollectionViewFlowLayout()
        let menu = ZLSwapMenu(frame: self.view.bounds, collectionViewLayout: layout)
        menu.dataSource = self
        menu.delegate = self
        menu.swapDelegate = self
        menu.register(CustomCell.self, forCellWithReuseIdentifier: "CustomCell")
        return menu
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.gray
        self.view.addSubview(self.menu)
        self.menu.center = self.view.center
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.titleLabel.text = String(self.dataArray[indexPath.row])
        cell.backgroundColor = indexPath.row == 7 ? UIColor.orange : UIColor.gray
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 80, height: 80)
    }
}

//MARK: 代理实现
extension ViewController: ZLSwapMenuDelegate {
    func didMoveReload(cell: UICollectionViewCell?, index: Int) {
        /// 刷新状态 保持下标 7 的颜色
        cell?.backgroundColor = index == 7 ? UIColor.orange : UIColor.gray
    }
    
    func didMove(from: Int, to: Int) {
        /// 交换数据
        (self.dataArray[from], self.dataArray[to]) = (self.dataArray[to], self.dataArray[from])
        print(self.dataArray)
    }
}

//MARK: cell
class CustomCell: UICollectionViewCell {
    /// title
    lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .center
        return label
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.titleLabel)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.titleLabel.center = self.contentView.center
    }
}

